<script setup lang="ts">
import { getPatientInfoByIdAPI, PostPatientAddAPI, updatePatientInfoAPI } from '@/apis/patient'
import type { PostPatientAddParams } from '@/types/patient'
import { ref } from 'vue'

const formData = ref<PostPatientAddParams>({
  name: '',
  gender: 1,
  idCard: '310101200201010717',
  defaultFlag: 0,
})
const formRef = ref<UniHelper.UniFormsInstance>()
const formRules = ref<UniHelper.UniFormsRules>({
  name: {
    rules: [
      { required: true, errorMessage: '请填写姓名' },
      { pattern: /^(?:[\u4e00-\u9fa5·]{2,16})$/, errorMessage: '请输入中文姓名' },
    ],
  },
  idCard: {
    rules: [
      { required: true, errorMessage: '请填写身份证号' },
      {
        pattern:
          /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/,
        errorMessage: '请输入正确的身份证号',
      },
    ],
  },
  gender: {
    rules: [
      { required: true, errorMessage: '请选择性别' },
      {
        validateFunction: (rule, value, data, callback) => {
          // 获取身份证号第17位
          const idCardGenderNumber = formData.value.idCard.charAt(16)
          if (+idCardGenderNumber % 2 !== value) {
            callback('性别与身份证号不匹配')
          }
          return true
        },
      },
    ],
  },
})
// 是否为默认就诊人
const onDefaultFlagChange = (e: UniHelper.SwitchOnChangeEvent) => {
  formData.value.defaultFlag = e.detail.value ? 1 : 0
}

const onSubmit = async () => {
  try {
    await formRef.value?.validate?.()
    if (props.id) {
      const { name, gender, idCard, defaultFlag, id } = formData.value
      await updatePatientInfoAPI({ name, gender, idCard, defaultFlag, id })
    } else {
      await PostPatientAddAPI(formData.value)
    }
    // 跳转回上一页
    uni.navigateBack()
    // 成功轻提示
    uni.showToast({ title: '保存成功', icon: 'success' })
  } catch {}
}
// 获取路径参数
const props = defineProps<{ id?: string }>()
// 动态修改标题
uni.setNavigationBarTitle({ title: props.id ? '编辑患者' : '新增患者' })

const getPatientInfoById = async () => {
  // 如果 props.id 存在，则查询患者详情
  if (props.id) {
    // 根据患者id获取详情
    const res = await getPatientInfoByIdAPI(props.id)
    // 保存患者信息，在表单中回显
    formData.value = res.data
  }
}
getPatientInfoById()
</script>

<template>
  <scroll-view>
    <view class="archive-page">
      <uni-forms
        border
        label-width="220rpx"
        ref="formRef"
        :rules="formRules"
        :modelValue="formData"
      >
        <uni-forms-item label="患者姓名" name="name">
          <uni-easyinput
            v-model="formData.name"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{
              color: '#121826',
              backgroundColor: 'transparent',
              disableColor: '#C3C3C5',
              borderColor: '#C3C3C5',
            }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写真实姓名"
          />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard">
          <uni-easyinput
            v-model="formData.idCard"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{
              color: '#121826',
              backgroundColor: 'transparent',
              disableColor: '#C3C3C5',
              borderColor: '#C3C3C5',
            }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写身份证号"
          />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender">
          <uni-data-checkbox
            v-model="formData.gender"
            selectedColor="#16C2A3"
            :localdata="[
              { text: '男', value: 1 },
              { text: '女', value: 0 },
            ]"
          />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人" name="name">
          <view class="uni-switch">
            <switch
              :checked="formData.defaultFlag === 1"
              @change="onDefaultFlagChange"
              color="#20c6b2"
              style="transform: scale(0.7)"
            />
          </view>
        </uni-forms-item>
        <button class="uni-button" @tap="onSubmit">保存</button>
      </uni-forms>
    </view>
    {{ formData }}
  </scroll-view>
</template>

<style lang="scss">
@import './index.scss';
</style>
